<!-- 关于 -->
<template>
  <div class="Box">
    <!-- pc注册 -->
    <el-form ref="loginForm" :model="formData" :rules="formRules" class="login">
      <div class="login-lift">
        <!-- 根据 isLogin 的值动态展示文字 -->
        <p>{{ isLogin ? "欢迎回来！" : "创建新用户" }}</p>
        <p>{{ isLogin ? "点击注册即可跳转！" : "点击登录即可跳转" }}</p>
        <!-- 将登录按钮添加点击事件，绑定 switchLoginStatus 方法 -->
        <el-button
          type="primary"
          round
          class="login-button"
          @click="switchLoginStatus"
          >{{ isLogin ? "注册" : "登录" }}</el-button
        >
        <router-link to="/Home">
          <el-button
            type="info"
            class="login-button"
            style="background-color: #ccc; border-color: #ccc; margin-top: 15px"
            round
            >返回首页</el-button
          >
        </router-link>
      </div>
      <div class="login-right">
        <p>{{ title }}</p>
        <!-- 如果 isLogin 为 false，则显示昵称、邮箱等输入框 -->
        <el-form-item v-if="!isLogin" label="用户：" prop="username">
          <el-input
            v-model="formData.username"
            class="input-style"
            placeholder="请输入账号"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin" label="昵称：" prop="nickName">
          <el-input
            v-model="formData.nickName"
            class="input-style"
            placeholder="请输入昵称"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin" label="邮箱：" prop="email">
          <el-input
            v-model="formData.email"
            class="input-style"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin" label="密码：" prop="password">
          <el-input
            v-model="formData.password"
            class="input-style"
            type="password"
            placeholder="请输入密码6-12英文，数字，下划线"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin" label="确认密码：" prop="confirmPassword">
          <el-input
            v-model="formData.confirmPassword"
            class="input-style"
            type="password"
            placeholder="请再次确认密码"
          ></el-input>
        </el-form-item>
        <el-input
          v-if="!isLogin"
          v-model="formData.code"
          placeholder="点击验证码即可刷新"
          style="width: 350px"
        >
          <template slot="append">
            <img
              :src="'data:image/jpeg;base64,' + codeImg"
              alt=""
              id="codeImg"
              style="height: 34px; width: 80px"
              @click="getCode()"
            />
          </template>
        </el-input>
        <!-- 如果 isLogin 为 true，则显示账号和密码输入框 -->
        <el-form-item v-if="isLogin" label="账号：" prop="username">
          <el-input
            v-model="formData.username"
            class="input-style"
            placeholder="请输入账号"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="isLogin" label="密码：" prop="password">
          <el-input
            v-model="formData.password"
            class="input-style"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-input
          v-if="isLogin"
          v-model="formData.code"
          placeholder="点击验证码即可刷新"
          style="width: 350px"
        >
          <template slot="append">
            <img
              :src="'data:image/jpeg;base64,' + codeImg"
              alt=""
              id="codeImg"
              style="height: 34px; width: 80px"
              @click="getCode()"
            />
          </template>
        </el-input>

        <!-- 忘记密码 -->
        <el-button type="text" @click="dialogVisible = true" v-if="isLogin"
          >忘记密码？</el-button
        >
        <el-dialog
          title="重置用户密码"
          :visible.sync="dialogVisible"
          width="85%"
          :before-close="handleClose"
          :modal="false"
        >
          <el-form-item label="账号：" prop="userName">
            <el-input
              v-model="userName"
              class="input-style"
              placeholder="请输入账号"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱：" prop="nemail">
            <el-input
              v-model="email"
              class="input-style"
              placeholder="请输入邮箱"
            ></el-input>
          </el-form-item>
          <el-form-item label="新密码：" prop="npassword">
            <el-input
              v-model="newPassword"
              class="input-style"
              type="password"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="新密码：" prop="npassword">
            <el-input
              v-model="password"
              class="input-style"
              type="password"
              placeholder="请再次输入密码"
            ></el-input>
          </el-form-item>
          <el-input
            v-model="code"
            placeholder="点击验证码即可刷新"
            style="width: 350px; margin-left: 80px"
          >
            <template slot="append">
              <img
                :src="'data:image/jpeg;base64,' + codeImg"
                alt=""
                id="codeImg"
                style="height: 34px; width: 80px"
                @click="getCode()"
              />
            </template>
          </el-input>
          <span slot="footer" class="dialog-footer">
            <el-button @click="handleCancel('formRules')">取 消</el-button>
            <el-button type="primary" @click="handleFindPassword"
              >重置</el-button
            >
          </span>
        </el-dialog>
        <!-- 将按钮的文字和样式通过表达式动态绑定 -->
        <el-form-item>
          <el-button
            type="primary"
            round
            class="register-button"
            :class="{ 'login-button': isLogin }"
            @click="isLogin ? gotoHome() : newRegister()"
            >{{ isLogin ? "登录" : "注册" }}</el-button
          >
        </el-form-item>
      </div>
    </el-form>
    <!-- 移动登录 -->
    <el-card class="mobileLogin" style="width: 85%; height: 650px">
      <p
        style="
          text-align: center;
          color: deepskyblue;
          font-size: 25px;
          margin-bottom: 10px;
        "
      >
        {{ isLogin ? "登录" : "注册" }}
      </p>

      <el-input
        v-if="isLogin"
        v-model="formData.username"
        class="input-style"
        placeholder="请输入账号"
        style="margin-bottom: 15px"
      ></el-input>

      <el-input
        v-if="isLogin"
        v-model="formData.password"
        class="input-style"
        type="password"
        placeholder="请输入密码"
        style="margin-bottom: 15px"
      ></el-input>

      <el-input
        v-if="isLogin"
        v-model="formData.code"
        placeholder="点击验证码即可刷新"
      >
        <template slot="append">
          <img
            :src="'data:image/jpeg;base64,' + codeImg"
            alt=""
            id="codeImg"
            style="height: 34px; width: 80px"
            @click="getCode()"
          />
        </template>
      </el-input>
      <!-- 移动注册 -->
      <el-input
        v-if="!isLogin"
        v-model="formData.username"
        class="input-style"
        placeholder="请输入账号"
        style="margin-bottom: 15px"
        @blur="checkUsername"
      ></el-input>
      <el-input
        v-if="!isLogin"
        v-model="formData.nickName"
        class="input-style"
        placeholder="请输入昵称"
        style="margin-bottom: 15px"
        @blur="checkNickname"
      ></el-input>
      <el-input
        v-if="!isLogin"
        v-model="formData.email"
        class="input-style"
        placeholder="请输入邮箱"
        style="margin-bottom: 15px"
        @blur="checkEmail"
      ></el-input>
      <el-input
        v-if="!isLogin"
        v-model="formData.password"
        class="input-style"
        type="password"
        placeholder="请输入密码6-12英文，数字，下划线"
        style="margin-bottom: 15px"
        @blur="checkPassword"
      ></el-input>
      <el-input
        v-if="!isLogin"
        v-model="formData.confirmPassword"
        class="input-style"
        type="password"
        placeholder="请再次确认密码"
        style="margin-bottom: 15px"
      ></el-input>
      <el-input
        v-if="!isLogin"
        v-model="formData.code"
        placeholder="点击验证码即可刷新"
      >
        <template slot="append">
          <img
            :src="'data:image/jpeg;base64,' + codeImg"
            alt=""
            id="codeImg"
            style="height: 34px; width: 80px"
            @click="getCode()"
          />
        </template>
      </el-input>
      <div style="text-align: center">
        <el-button type="primary" @click="gotoHome()" v-if="isLogin" round
          >登录</el-button
        >
        <el-button type="primary" @click="newRegister()" v-if="!isLogin" round
          >注册</el-button
        >
        <el-button
          type="info"
          round
          class="login-button"
          @click="switchLoginStatus"
          >{{ isLogin ? "前往注册" : "返回登录" }}</el-button
        >
        <router-link to="/Home"
          ><el-button type="success" round>首页</el-button></router-link
        >
      </div>
    </el-card>
  </div>
</template>


<script>
import { userLogin, userRegister, handleForgotPassword } from "../api/user.js";
import { getCodes } from "../api/code.js";
import { setToken } from "../utils/auth.js";
import { Message } from "element-ui";
export default {
  data() {
    return {
      dialogVisible: false,

      isLogin: true, // 默认为登录状态
      title: "欢迎来到栩栩如生博客",
      code: "",
      codeImg: "",
      loading: false,
      loadingText: "加载中...",
      loadingBackground: "rgba(0, 0, 0, 0.8)",
      clickCount: 0, // 点击计数器
      clickLimit: 10, // 点击限制
      clickInterval: 60000, // 点击间隔时间（毫秒）
      clickTimer: null, // 定时器

      userName: "",
      email: "", //邮箱
      password: "", //密码
      newPassword: "", //新密码
      formData: {
        // 表单数据
        username: "",
        password: "",
        nickName: "",
        email: "",
        confirmPassword: "",
        code: "",
      },
      formRules: {
        // 表单验证规则
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            pattern: /^[A-Za-z0-9]+$/,
            message: "只能输入英文和数字",
            trigger: "blur",
          },
          {
            min: 4,
            max: 10,
            message: "长度必须在6到10之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern: /^[A-Za-z0-9]+$/,
            message: "只能输入英文和数字",
            trigger: "blur",
          },
          {
            min: 6,
            max: 10,
            message: "长度必须在6到10之间",
            trigger: "blur",
          },
        ],
        nickName: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 4,
            max: 10,
            message: "昵称长度需要在4到10个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱格式",
            trigger: ["blur", "change"],
          },
        ],
        confirmPassword: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value !== this.formData.password) {
                callback(new Error("两次输入的密码不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  //注册组件
  components: {
    // "sg-nav": header,
  },
  methods: {
    checkUsername() {
      const username = this.formData.username;
      const usernameRegex = /^[A-Za-z0-9_]{3,10}$/;

      if (!usernameRegex.test(username)) {
        this.$message({
          type: "warning",
          message: "账号格式不正确，请输入3-10位的英文、数字和下划线",
        });
      }
    },
    checkNickname() {
      const nickname = this.formData.nickName;
      if (nickname.length < 2 || nickname.length > 10) {
        this.$message({
          type: "warning",
          message: "昵称长度应为4到10位",
        });
      }
    },
    checkEmail() {
      const email = this.formData.email;
      const emailRegex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;

      if (!emailRegex.test(email)) {
        this.$message({
          type: "warning",
          message: "请输入有效的邮箱地址",
        });
      }
    },
    checkPassword() {
      const password = this.formData.password;
      const passwordRegex = /^[A-Za-z0-9_]{6,12}$/;

      if (
        password.length < 6 ||
        password.length > 12 ||
        !passwordRegex.test(password)
      ) {
        this.$message({
          type: "warning",
          message: "密码格式不正确，请输入6-12位的英文、数字和下划线",
        });
      }
    },

    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 关闭弹出框、清除表单数据等操作
    handleCancel() {
      this.dialogVisible = false;
      this.userName = "";
      this.email = "";
      this.newPassword = "";
      this.password = "";
      this.code = "";
    },
    async handleFindPassword() {
      var that = this;
      // 首先进行表单验证，比如用户名和邮箱是否为空等等（这里简单处理）
      if (!this.userName || !this.email) {
        this.$message.error("请输入用户名和邮箱");
        return;
      }
      if (!this.newPassword || !this.password) {
        this.$message.error("请填写新密码和确认密码");
        return;
      }

      if (this.newPassword !== this.password) {
        this.$message.error("两次输入的密码不一致，请重新输入！");
        return;
      }

      try {
        handleForgotPassword(
          this.userName,
          this.email,
          this.password,
          this.code
        )
          .then((response) => {
            (this.newPassword = ""),
              (this.password = ""),
              (this.userName = ""),
              (this.email = ""),
              (this.code = ""),
              this.$message.success("修改成功");
            this.dialogVisible = false; // 隐藏找回密码对话框
          })
          .catch((error) => {
            console.error(error);
          });
      } catch (error) {
        console.log(error); // 输出异常信息，方便排查
        this.$message.error("找回密码失败，请重试！");
      }
    },

    //获取验证码
    getCode() {
      if (this.clickCount < this.clickLimit) {
        // 判断是否达到点击限制
        this.loading = true;
        getCodes().then((response) => {
          this.codeImg = response;
          setTimeout(() => {
            this.loading = false;
          }, 1000);
        });
        this.clickCount++; // 增加点击计数器

        // 如果定时器还在运行，则清除之前的定时器
        if (this.clickTimer) {
          clearTimeout(this.clickTimer);
        }

        // 设置一个定时器，在点击间隔时间后重置点击计数器
        this.clickTimer = setTimeout(() => {
          this.clickCount = 0; // 重置点击计数器
          this.clickTimer = null; // 清空定时器
        }, this.clickInterval);
      } else {
        this.$message.error("点击验证码次数过多，请一分钟之后重试！"); // 提示用户点击次数过多
      }
    },

    switchLoginStatus() {
      this.isLogin = !this.isLogin;
      this.title = this.isLogin ? "欢迎来到栩栩如生博客" : "";
      this.clearForm();
      if (!this.isLogin) {
        this.getCode(); // 点击切换登录状态时重新获取验证码
      }
      if (this.isLogin) {
        this.getCode();
      }
    },
    newRegister() {
      // 提交表单，执行注册操作
      if (this.formData.username === "" || this.formData.password === "") {
        this.$message.error("信息为空，请按照要求填写！");
        return;
      }
      var that = this;
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // 验证通过，执行注册操作
          userRegister(
            that.formData.username,
            that.formData.nickName,
            that.formData.email,
            that.formData.password,
            that.formData.code
          )
            .then((response) => {
              //注册成功后调整到登录
              this.$message.success("注册成功！正在跳转到登录页面...");
              setTimeout(() => {
                userLogin(
                  this.formData.username,
                  this.formData.password,
                  this.formData.code
                )
                  .then((response) => {
                    setToken(response.token);
                    localStorage.setItem(
                      "userInfo",
                      JSON.stringify(response.userInfo)
                    );
                    setTimeout(() => {
                      location.reload(); // 或者使用 this.$router.push({ path: '/' }) 来跳转到当前页面
                    }, 1000);
                    this.$message.success("登录成功");
                    // 在用户登录成功后，保存登录时间戳
                    localStorage.setItem("loginTime", Date.now());
                    this.$router.push({ path: "/" });
                  })

                  .catch((error) => {
                    this.$message.error("自动登录失败: " + error.message);
                  });
              }, 3000);
            })
            .catch((error) => {
              that.fullscreenLoading = false;
            });
        } else {
          this.$message.error("表单填写不完整或有误，请检查后重试");
        }
      });
    },
    gotoHome() {
      // 跳转到首页
      // 在此处编写登录逻辑
      //console.log("登录");
      if (this.formData.username === "" || this.formData.password === "") {
        this.$message.error("用户名或密码不能为空");
        return;
      }
      // 获取用户输入的验证码
      let code = this.formData.code;
      if (!code) {
        // 如果未输入验证码
        this.$message.error("请输入验证码");
        return;
      }

      //用户登录
      userLogin(
        this.formData.username,
        this.formData.password,
        this.formData.code
      ).then((response) => {
        // 登录成功记录token和用户信息，登录失败给对应提示
        setToken(response.token);
        // 存储用户信息
        localStorage.setItem("userInfo", JSON.stringify(response.userInfo));
        if (localStorage.getItem("logUrl")) {
          this.$router.push({ path: localStorage.getItem("logUrl") });
        } else {
          this.$router.push({ path: "/" });
        }
        this.$message.success("登录成功");
        this.$router.push({ path: "/" });
        setTimeout(() => {
          location.reload(); // 或者使用 this.$router.push({ path: '/' }) 来跳转到当前页面
        }, 1000);
      });
    },
    clearForm() {
      // 清空表单数据和验证状态
      this.$refs.loginForm.resetFields();
    },
  },

  mounted() {
    this.getCode();
    this.$message = Message;
  },
};
</script>

<style lang="less" scoped>
.el-input-group {
  margin-bottom: 20px;
}
.el-input-group /deep/ .el-input-group__append {
  border-left: 0;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.Box {
  background-image: url("https://images.pexels.com/photos/1933319/pexels-photo-1933319.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1");
  // background-color: rgb(133, 133, 133,0.4);
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* 可能需要根据实际情况设置高度 */
}

.login {
  width: 60%;
  height: 780px;
  background-color: #fdfdfd83;
  border-radius: 25px;
  display: flex;
  flex-direction: row;

  .login-lift {
    background: #61dac069;
    backdrop-filter: blur(15px);
    border-radius: 25px 0 0 25px;
    flex-basis: 35%;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    p:first-child {
      font-size: 36px;
      color: white;
      font-weight: bold;
      padding: 20px;
    }
    p {
      color: white;
      font-size: 18px;
      padding: 25px;
    }
    .login-button {
      width: 200px;
      height: 50px;
      border-radius: 25px;
    }
  }

  .login-right {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-size: 25px;
    color: #ffffff;
    // font-weight: bold;
    flex-basis: 65%;
    background: #ffffff34;
    backdrop-filter: blur(15px);
    border-radius: 0 25px 25px 0;
    p {
      margin-bottom: 25px;
    }
    .input-style {
      width: 350px;
      height: 45px;
      margin-bottom: 10px;
    }
    .input-style input[type="text"] {
      border-radius: 25px;
    }

    .register-button {
      width: 200px;
      height: 50px;
      border-radius: 25px;
      display: inline-block;
    }
  }
}
.login-right /deep/ .el-form-item {
  margin-bottom: 20px;
}
@media (max-width: 767px) {
  .login {
    //min-width: 100%;
    display: none;
  }
  .mobileLogin {
    display: block;
  }
}
@media (min-width: 768px) {
  .login {
    //min-width: 100%;
    // display: block;
  }
  .mobileLogin {
    display: none;
  }
}
</style>>
